package pl.task;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

public class TaskEntityHelper
{
    private static final String TABLE_NAME = "Task";
    private static final String INSERT = "INSERT INTO " + TABLE_NAME + "("
        + "nazwa, "
        + "opis)"
        + " values (?,?)";
    private static final String UPDATE = "UPDATE " + TABLE_NAME + " SET "
        + "nazwa=?, "
        + "opis=?"
        + " WHERE _id = ?";

    private SQLiteDatabase db;
    private SQLiteStatement insertStatement;
    private SQLiteStatement updateStatement;

    public TaskEntityHelper(SQLiteDatabase db)
    {
        super();

        this.db = db;
        insertStatement = this.db.compileStatement(INSERT);
        updateStatement = this.db.compileStatement(UPDATE);
    }

    public static void createTable(SQLiteDatabase db)
    {
        db.execSQL("CREATE TABLE " + TABLE_NAME + "("
            + "_id INTEGER PRIMARY KEY, "
            + "nazwa TEXT, "
            + "opis TEXT)");
    }

    public static void dropTable(SQLiteDatabase db)
    {
       db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    }

    public long insert(ContentValues values)
    {
        insertStatement.clearBindings();
        insertStatement.bindString(1, values.getAsString("nazwa"));
        insertStatement.bindString(2, values.getAsString("opis"));

        return insertStatement.executeInsert();
    }

    public long update(ContentValues values)
    {
        updateStatement.clearBindings();
        updateStatement.bindString(1, values.getAsString("nazwa"));
        updateStatement.bindString(2, values.getAsString("opis"));
        updateStatement.bindLong(3, values.getAsLong("_id"));

        return updateStatement.executeInsert();
    }

    public void deleteAll()
    {
        db.delete(TABLE_NAME, null, null);
    }

    public Cursor query(String[] projection, String selection, String[] selectionArgs, String sortOrder)
    {
        return db.query(TABLE_NAME, projection, null, null, null, null, sortOrder);
    }
}
